# Maroonpu at 2018/1/25

import socket, threading

serverIP   = '192.168.123.158'
serverPort = 8988


def tcplink(sock, addr):
    # common var
    global connectFlag

    # connectFlag 0->NOT YET  1->FINISH
    connectFlag = 0

    print('Accept new connection from %s:%s...' % addr)

    while True:
        data = sock.recv(1024)
        # widora connect
        if -1 != str(data, encoding="utf-8").find("widoraConnect"):
            print("connect widora")
            # send flag to widora
            sock.send(b"serverRcv")

            connectFlag = 1
            break
        # android connect
        elif -1 != str(data, encoding='utf-8').find('androidConnect'):
            print('connect android')
            while True:
                if 1 == connectFlag:
                    # send flag to android
                    sock.send(b"wifiCompeleted")
                    connectFlag = 0
                    break
            break
        # etc
        else:
            break

    sock.close()
    print('Connection from %s:%s closed.' % addr)
    print(connectFlag)



s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

s.bind((serverIP,serverPort))

s.listen(5)

print('Waiting for connection...')

while True:
    sock, addr = s.accept()
    t = threading.Thread(target=tcplink,args=(sock, addr))
    t.start()

